Bash遍历字符串列表 您所在的位置:网站首页 bash list Bash遍历字符串列表

Bash遍历字符串列表

#Bash遍历字符串列表| 来源: 网络整理| 查看: 265

大家知道,通过python可以很容易实现各类数据结构,例如列表。但在bash中,实现一个列表相对来说会比较复杂。

笼统的说,bash实现字符串遍历的方式,实际是定义一个数组然后遍历其元素

示例1:在for循环中迭代多个单词的字符串#!/bin/bash # Read a string with spaces using for loop for value in I like programming do echo $value done

结果

$ sh test1.sh I like programming示例2:使用for循环迭代字符串变量

在变量StringVal中分配文本,并使用for循环读取此变量的值。最终效果跟上例相同

#!/bin/bash # Define a string variable with a value StringVal="Welcome to linuxhint" # Iterate the string variable using for loop for val in $StringVal; do echo $val done

结果

$ sh test2.sh Welcome to linuxhint示例3:迭代字符串值的数组

在此脚本中使用类型声明字符串值的数组。数组中包含空格的两个值是“ Linux Mint”和“ Red Hat Linux”。该脚本将这些值拆分为多个单词并将其打印为单独的值,从而生成输出。但这不是正确的输出。下一个示例显示了此类问题的解决方案。

#!/bin/bash # Declare an array of string with type declare -a StringArray=("Linux Mint" "Fedora" "Red Hat Linux" "Ubuntu" "Debian" ) # Iterate the string array using for loop for val in ${StringArray[@]}; do echo $val done

结果

$ sh test3.sh Linux Mint Fedora Red Hat Linux Ubuntu Debian示例4:将多个单词的字符串值打印为单个值#!/bin/bash # Declare a string array with type declare -a StringArray=("Windows XP" "Windows 10" "Windows ME" "Windows 8.1" "Windows Server 2016" ) # Read the array values with space for val in "${StringArray[@]}"; do echo $val done

结果:

$ sh test4.sh Windows XP Windows 10 Windows ME Windows 8.1 Windows Server 2016示例5:使用'*迭代数组的字符串值#!/bin/bash #Declare a string array LanguageArray=("PHP" "Java" "C#" "C++" "VB.Net" "Python" "Perl") # Print array values in lines echo "Print every element in new line" for val1 in ${LanguageArray[*]}; do echo $val1 done echo "" # Print array values in one line echo "Print all elements in a single line" for val2 in "${LanguageArray[*]}"; do echo $val2 done echo ""

结果:

$ sh test5.sh Print every element in new line PHP Java C# C++ VB.Net Python Perl Print all elements in a single line PHP Java C# C++ VB.Net Python Perl示例6:迭代以逗号分隔的字符串值

在这里,逗号(,)用于分割字符串值。 IFS变量用于设置字段分隔符。

#!/bin/bash DataList=" HTML5, CCS3, BootStrap, JQuery " Field_Separator=$IFS # set comma as internal field separator for the string list IFS=, for val in $DataList; do echo $val done IFS=$Field_Separator

结果:

$ sh test6.sh HTML5 CCS3 BootStrap JQuery示例7:多个字符串数组一起读取

示例演示怎么合并多个数据并遍历出来

#! /bin/sh str_array1=("Magento 2.2.4" "WooCommerce") str_array2=("CodeIgnitor" "Laravel") combine=(str_array1 str_array2) for arrItem in ${combine[@]} do eval 'for val in "${'$arrItem'[@]}";do echo "$val";done' done

结果:

$ sh test7.sh Magento 2.2.4 WooCommerce CodeIgnitor Laravel示例8:使用模式读取字符串列表

在这里,“ /,/”模式用于根据逗号分割字符串值。

#! /bin/sh # Define a list of string variable stringList=WordPress,Joomla,Magento # Use comma as separator and apply as pattern for val in ${stringList//,/ } do echo $val done

结果:

$ sh test8.sh WordPress Joomla Magento

参考:

https://linuxhint.com/bash_loop_list_strings/


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有